package core.exception;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import core.domain.Result;
import core.enums.ResultCode;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Collection;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<?> exceptionHandler(HttpRequestMethodNotSupportedException e,
                                      HttpServletRequest request) {
        log.error("{}, 请求方式不支持: {}", request.getRequestURI(), e.getMessage());
        return Result.fail(ResultCode.FAILED, e.getMessage());
    }

    @ExceptionHandler(ServiceException.class)
    public Result<?> exceptionHandler(ServiceException e, HttpServletRequest request) {
        ResultCode resultCode = e.getResultCode();
        log.error("{} 发生业务异常: {}", request.getRequestURI(), resultCode.getMessage(), e);
        return Result.fail(resultCode);
    }

    @ExceptionHandler(BindException.class)
    public Result<?> exceptionHandler(BindException e, HttpServletRequest request) {
        log.error("{} 发生参数异常: {}", request.getRequestURI(), e.getMessage(), e);
        String message = join(e.getAllErrors(), DefaultMessageSourceResolvable::getDefaultMessage, ", ");
        return Result.fail(ResultCode.FAILED_PARAMS_VALIDATE, message);
    }

    private <E> String join(Collection<E> collection, Function<E, String>
            function, CharSequence delimiter) {
        if (CollUtil.isEmpty(collection)) {
            return StrUtil.EMPTY;
        }
        return collection.stream().map(function).filter(Objects::nonNull).collect(Collectors.joining(delimiter));
    }

    @ExceptionHandler(RuntimeException.class)
    public Result<?> exceptionHandler(RuntimeException e, HttpServletRequest request) {
        log.error("{} 发生运行时异常: {}", request.getRequestURI(), e.getMessage(), e);
        return Result.fail(ResultCode.ERROR, e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result<?> exceptionHandler(Exception e, HttpServletRequest request) {
        log.error("{} 发生系统异常: {}", request.getRequestURI(), e.getMessage(), e);
        return Result.fail(ResultCode.ERROR);
    }
}
